package com.minyifang.wcspf.work.ui.home.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpFragment;
import com.minyifang.wcspf.common.config.user.UserManager;
import com.minyifang.wcspf.common.utils.ArrayUtil;
import com.minyifang.wcspf.common.utils.ImageUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.common.widgets.CustomScrollView;
import com.minyifang.wcspf.common.widgets.LooperTextView;
import com.minyifang.wcspf.work.common.MyWebViewActivity;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.Global;
import com.minyifang.wcspf.work.ui.goods.activities.GoodsDetailsActivity;
import com.minyifang.wcspf.work.ui.home.activities.MainActivity;
import com.minyifang.wcspf.work.ui.home.activities.NewsListActivity;
import com.minyifang.wcspf.work.ui.home.activities.SearchActivity;
import com.minyifang.wcspf.work.ui.home.activities.TakeGoodsActivity;
import com.minyifang.wcspf.work.ui.home.model.AdvertisingBean;
import com.minyifang.wcspf.work.ui.home.model.BannerBean;
import com.minyifang.wcspf.work.ui.home.model.CategoryBean;
import com.minyifang.wcspf.work.ui.home.model.GoodsBean;
import com.minyifang.wcspf.work.ui.home.model.HomePage1Bean;
import com.minyifang.wcspf.work.ui.home.model.NewsBean;
import com.minyifang.wcspf.work.ui.home.model.RecommendGoodsBean;
import com.minyifang.wcspf.work.ui.home.presenter.HomePage1Presenter;
import com.minyifang.wcspf.work.ui.home.view.HomePage1View;
import com.minyifang.wcspf.work.ui.user.activities.MessageActivity;
import com.minyifang.wcspf.work.ui.user.activities.MyCollectionActivity;
import com.minyifang.wcspf.work.ui.user.activities.MyOrderListActivity;
import com.minyifang.wcspf.work.ui.user.activities.PriceChangeActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomePage1Fragment extends BaseMvpFragment<HomePage1View, HomePage1Presenter> implements HomePage1View {

    private static final long TIME_BANNER_LOOPER = 4000;
    private int mTitleBarHeight;
    private boolean mIsTitleBgTranslucent;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.ll_net_error)
    LinearLayout mLlError;
    @BindView(R.id.ll_load_view)
    LinearLayout ll_load_view;

    @BindView(R.id.tv_city)
    TextView tv_city;
    @BindView(R.id.tv_store)
    TextView tv_store;
    @BindView(R.id.iv_message)
    ImageView iv_message;

    @BindView(R.id.cb_banner)
    ConvenientBanner<String> mBanner;
    @BindView(R.id.rv_category)
    RecyclerView mRvCategory;
    @BindView(R.id.lt_view)
    LooperTextView mLooperTextView;
    @BindView(R.id.rv_special_sale)
    RecyclerView mRvSpecialSale;
    @BindView(R.id.ll_special_sale)
    LinearLayout ll_special_sale;

    @BindView(R.id.ll_advertising)
    LinearLayout ll_advertising;
    @BindView(R.id.iv_advertising1)
    ImageView iv_advertising1;
    @BindView(R.id.iv_advertising2)
    ImageView iv_advertising2;
    @BindView(R.id.iv_advertising3)
    ImageView iv_advertising3;

    @BindView(R.id.rv_new_recommend)
    RecyclerView mRvNewRecommend;

    @BindView(R.id.scrollView)
    CustomScrollView scrollView;
    @BindView(R.id.goto_top)
    ImageView goto_top;

    private List<BannerBean> mBannerList;
    private List<CategoryBean> mCategoryList;
    private List<NewsBean> mNewsList;
    private List<GoodsBean> mGoodsList;
    private List<GoodsBean> mRecommendList;

    private CategoryAdapter mCategoryAdapter;
    private SpecialSaleAdapter mSpecialSaleAdapter;
    private RecommendGoodsAdapter mRecommendGoodsAdapter;

    private boolean isLoginState;
    private int pageIndex = 0;


    public HomePage1Fragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isLoginState = UserManager.getInstance().isLogin();
    }

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_home_page1;
    }

    @Override
    protected HomePage1Presenter createPresenter() {
        return new HomePage1Presenter();
    }

    @Override
    protected void lazyLoadData() {
        getPresenter().getData();
        getRecommendGoodsListData(false);
    }

    @Override
    protected void initView() {
        mBannerList = new ArrayList<>();
        mCategoryList = new ArrayList<>();
        mNewsList = new ArrayList<>();
        mGoodsList = new ArrayList<>();
        mRecommendList = new ArrayList<>();

        mBanner.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = mBanner.getLayoutParams();
                layoutParams.height = mBanner.getWidth() / 2;
                mBanner.setLayoutParams(layoutParams);
                mBanner.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        mCategoryAdapter = new CategoryAdapter();
        mRvCategory.setAdapter(mCategoryAdapter);
        mRvCategory.setLayoutManager(new GridLayoutManager(getActivity(), 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        mSpecialSaleAdapter = new SpecialSaleAdapter();
        mRvSpecialSale.setAdapter(mSpecialSaleAdapter);
        mRvSpecialSale.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });


        mRecommendGoodsAdapter = new RecommendGoodsAdapter();
        mRvNewRecommend.setAdapter(mRecommendGoodsAdapter);
        mRvNewRecommend.setLayoutManager(new GridLayoutManager(getActivity(), 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });


        goto_top.setAlpha(0f);
        scrollView.setScrollOffsetChangedListener((l, t, oldl, oldt) -> {
            LogUtil.e("滑动" + t + "-------" + oldt);
            if (t > 1000) {
                goto_top.setEnabled(true);
                goto_top.animate().translationY(0).alpha(1).setDuration(220).start();
            } else {
                goto_top.setEnabled(false);
                goto_top.animate().translationY(goto_top.getHeight()).alpha(0).setDuration(220).start();
            }
        });
    }

    @OnClick(R.id.goto_top)
    void goToTop() {
        scrollView.fling(0);
        scrollView.smoothScrollTo(0, 0);
    }

    @Override
    protected void initData() {

        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            getRecommendGoodsListData(false);
        });

        mRefreshLayout.setOnLoadMoreListener(refreshLayout ->
                getRecommendGoodsListData(true)
        );

    }

    void getRecommendGoodsListData(boolean isLoadMore) {
        if (isLoadMore) {
            pageIndex++;
        } else {
            pageIndex = 0;
        }
        getPresenter().getRecommendGoodsList(pageIndex, 9);
    }


    @Override
    public void showHomeData(HttpRespond<HomePage1Bean> respond) {
        if (respond.result == 1) {
            tv_city.setText(respond.data.getCity());
            tv_store.setText(respond.data.getStore());
            UserManager.getInstance().saveStoreName(respond.data.getStore());
            if (respond.data.getMessageLogicList() == 1) {
                iv_message.setVisibility(View.VISIBLE);
            } else
                iv_message.setVisibility(View.GONE);

            setBanner(respond.data.getBannerList());
            setCategory(respond.data.getSuperList());
            setTips(respond.data.getMicroList());
            setSpecialSale(respond.data.getActivityList());
            setAdvertising(respond.data.getAdvertisingsList());
        } else
            ToastHelper.getInstance(getActivity()).showWarn(respond.message);
        ll_load_view.postDelayed(() -> ll_load_view.setVisibility(View.GONE),500);
    }

    @Override
    public void showRecommendGoodsList(HttpRespond<RecommendGoodsBean> respond) {
        //ll_load_view.setVisibility(View.GONE);
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadMore();
        if (respond.result == 1) {
            if (respond.data.getCommodityList() != null && respond.data.getCommodityList().size() > 0) {
                mRecommendList.addAll(respond.data.getCommodityList());
                pageIndex++;
            }
            mRecommendGoodsAdapter.notifyDataSetChanged();

        } else
            ToastHelper.getInstance(getActivity()).showWarn(respond.message);

    }


    /**
     * Banner图
     *
     * @param bannerList
     */
    void setBanner(List<BannerBean> bannerList) {

        mBannerList.clear();
        mBannerList.addAll(bannerList);
        mBanner.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new NetImageLoadHolder();
            }
        }, ArrayUtil.listConvertToStringList(mBannerList, BannerBean::getPic));

        mBanner.setOnItemClickListener(position -> handlerClickEvent(bannerList.get(position).getType(), bannerList.get(position).getVal()));
        mBanner.startTurning(TIME_BANNER_LOOPER);
    }

    /**
     * 分类
     *
     * @param superList
     */
    void setCategory(List<CategoryBean> superList) {
        mCategoryList.clear();
        mCategoryList.addAll(superList);
        mCategoryAdapter.notifyDataSetChanged();

    }

    /**
     * 微头条
     *
     * @param microList
     */
    void setTips(List<NewsBean> microList) {
        mNewsList.clear();
        mNewsList.addAll(microList);
        mLooperTextView.setTipList(ArrayUtil.listConvertToStringList(mNewsList, newsBean -> newsBean.getTitle()));
    }

    /**
     * 今日特价
     *
     * @param activityList
     */
    void setSpecialSale(List<GoodsBean> activityList) {
        mGoodsList.clear();
        mGoodsList.addAll(activityList);
        ll_special_sale.setVisibility(mGoodsList.size() > 0 ? View.VISIBLE : View.GONE);
        mSpecialSaleAdapter.notifyDataSetChanged();
    }

    /**
     * 三张广告位
     *
     * @param advertisingList
     */
    void setAdvertising(List<AdvertisingBean> advertisingList) {
        if (advertisingList.size() > 2) {
            ll_advertising.setVisibility(View.VISIBLE);
            ImageUtils.getInstance().showImage(advertisingList.get(0).getPic(), iv_advertising1);
            ImageUtils.getInstance().showImage(advertisingList.get(1).getPic(), iv_advertising2);
            ImageUtils.getInstance().showImage(advertisingList.get(2).getPic(), iv_advertising3);
        } else
            ll_advertising.setVisibility(View.GONE);

        iv_advertising1.setOnClickListener(v -> {
            handlerClickEvent(advertisingList.get(0).getType(), advertisingList.get(0).getVal());
        });

        iv_advertising2.setOnClickListener(v -> {
            handlerClickEvent(advertisingList.get(1).getType(), advertisingList.get(1).getVal());
        });

        iv_advertising3.setOnClickListener(v -> {
            handlerClickEvent(advertisingList.get(2).getType(), advertisingList.get(2).getVal());
        });
    }

    /**
     * banner 广告位点击跳转
     *
     * @param type type:0二级分类， 1商品详情， 2H5页面, 3搜索关键字
     * @param val
     */
    private void handlerClickEvent(int type, String val) {
        switch (type) {
            case 0:
                if (val.contains(",")) {
                    String[] split = val.split(",");
                    ((MainActivity) getActivity()).checkSubClass(split[0], split[1]);
                } else
                    ((MainActivity) getActivity()).checkClass(val);

                break;
            case 1:
                GoodsDetailsActivity.start(getContext(), val);
                break;
            case 2:
                startActivity(MyWebViewActivity.getIntent(getActivity(), "", val));
                break;
            case 3:
                SearchActivity.start(getActivity(), val);
                break;
        }
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void hideLoadingView() {

    }

    @Override
    public void onNetworkError() {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mLlError.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.tv_get_data)
    void tv_get_data() {
        mLlError.setVisibility(View.GONE);
        getRecommendGoodsListData(false);
    }


    @OnClick(R.id.lt_view)
    void gotoNewsList() {
        startActivity(new Intent(getActivity(), NewsListActivity.class));
    }

    @Override
    public void onPause() {
        super.onPause();
        mBanner.stopTurning();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isLoginState != UserManager.getInstance().isLogin()) {
            isLoginState = UserManager.getInstance().isLogin();
            getPresenter().getData();
        }
        mBanner.startTurning(TIME_BANNER_LOOPER);
    }

    /**
     * 我要取货
     */
    @OnClick(R.id.ll_take_goods)
    void gotoTakeGoods() {

        if (Global.checkLogin(getContext())) {
            startActivity(new Intent(getActivity(), TakeGoodsActivity.class));
        }
        //        startActivity(new Intent(getActivity(), GoodsDetailsActivity.class));
    }

    /**
     * 消息
     */
    @OnClick(R.id.fl_message)
    void fl_message() {
        startActivity(new Intent(getActivity(), MessageActivity.class));
    }

    /**
     * 切换门店
     */
    @OnClick(R.id.ll_choose_store)
    void ll_choose_store() {
        //startActivity(new Intent(getActivity(), ChooseStoreActivity.class));
    }

    //搜索
    @OnClick(R.id.iv_search)
    void iv_search() {
        SearchActivity.start(getActivity(), null);
    }

    //我常购买
    @OnClick(R.id.ll_open_buy)
    void ll_open_buy() {
        if (Global.checkLogin(getContext())) {
            startActivity(new Intent(getActivity(), MyCollectionActivity.class));
        }
    }

    //我的订单
    @OnClick(R.id.ll_my_order)
    void ll_my_order() {
        if (Global.checkLogin(getContext())) {
            startActivity(new Intent(getActivity(), MyOrderListActivity.class));
        }
    }

    //今日特价
    @OnClick(R.id.ll_special_sale)
    void ll_special_sale() {
        if (Global.checkLogin(getContext()))
            PriceChangeActivity.start(getContext(), true);
    }


    public static class NetImageLoadHolder implements Holder<String> {
        private ImageView image_lv;

        //可以是一个布局也可以是一个Imageview
        @Override
        public ImageView createView(Context context) {
            image_lv = new ImageView(context);
            image_lv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return image_lv;

        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            ImageUtils.getInstance().showImage(data, image_lv);
        }
    }

    /**
     * 分类适配器
     */
    class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.Holder> {
        @NonNull
        @Override
        public CategoryAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_home_category, parent, false));
            holder.itemView.setOnClickListener(v -> ((MainActivity) getActivity()).checkClass(mCategoryList.get(holder.getAdapterPosition()).getID()));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull CategoryAdapter.Holder holder, int position) {
            CategoryBean categoryBean = mCategoryList.get(position);
            holder.item_name.setText(categoryBean.getName());
            ImageUtils.getInstance().showImage(categoryBean.getIcon(), holder.item_pic);
        }

        @Override
        public int getItemCount() {
            return mCategoryList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {

            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_name)
            TextView item_name;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /**
     * 今日特价适配器
     */
    class SpecialSaleAdapter extends RecyclerView.Adapter<SpecialSaleAdapter.Holder> {
        @NonNull
        @Override
        public SpecialSaleAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(getLayoutInflater().inflate(R.layout.item_special_goods_list, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull SpecialSaleAdapter.Holder holder, int position) {

            GoodsBean goodsBean = mGoodsList.get(position);
            if (goodsBean.getIsNew() == 1)
                holder.item_isNew.setVisibility(View.VISIBLE);
            else
                holder.item_isNew.setVisibility(View.GONE);

            ImageUtils.getInstance().showImage(goodsBean.getDeputyPic(), holder.item_pic);
            holder.item_name.setText(goodsBean.getName());
            holder.item_original_price.setText(String.format("￥%s", goodsBean.getMarketPrice()));
            holder.item_original_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.item_discount_price.setText(String.format("￥%s", goodsBean.getUnitPrice()));
            holder.item_unit.setText("/" + goodsBean.getPriceName());


            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(getContext(), goodsBean.getID()));

            holder.item_car.setOnClickListener(v -> Global.showSpecificationDialog(getActivity(), goodsBean.getID()));

        }

        @Override
        public int getItemCount() {
            return mGoodsList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_name)
            TextView item_name;
            @BindView(R.id.item_original_price)
            TextView item_original_price;
            @BindView(R.id.item_discount_price)
            TextView item_discount_price;
            @BindView(R.id.item_unit)
            TextView item_unit;
            @BindView(R.id.item_car)
            ImageView item_car;


            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /**
     * 新品推荐适配器
     */
    class RecommendGoodsAdapter extends RecyclerView.Adapter<RecommendGoodsAdapter.Holder> {

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_recommend_goods_list, parent, false));
            holder.item_pic.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewGroup.LayoutParams layoutParams = holder.item_pic.getLayoutParams();
                    layoutParams.height = holder.item_pic.getWidth();
                    holder.item_pic.setLayoutParams(layoutParams);
                    holder.item_pic.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
            return holder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull RecommendGoodsAdapter.Holder holder, int position) {

            GoodsBean goodsBean = mRecommendList.get(position);
            if (goodsBean.getIsNew() == 1)
                holder.item_isNew.setVisibility(View.VISIBLE);
            else
                holder.item_isNew.setVisibility(View.GONE);

            ImageUtils.getInstance().showImage(goodsBean.getDeputyPic(), holder.item_pic);
            holder.item_name.setText(goodsBean.getName());
            holder.item_original_price.setText(goodsBean.getMarketPrice());
            holder.item_original_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.item_discount_price.setText(String.format("￥%s", goodsBean.getUnitPrice()));
            holder.item_unit.setText("/" + goodsBean.getPriceName());


            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(getContext(), goodsBean.getID()));
            holder.item_car.setOnClickListener(v -> Global.showSpecificationDialog(getActivity(), goodsBean.getID()));
        }

        @Override
        public int getItemCount() {
            return mRecommendList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_name)
            TextView item_name;
            @BindView(R.id.item_original_price)
            TextView item_original_price;
            @BindView(R.id.item_discount_price)
            TextView item_discount_price;
            @BindView(R.id.item_unit)
            TextView item_unit;
            @BindView(R.id.item_car)
            ImageView item_car;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

}
